package com.core.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.core.CoreApplication;
import com.core.activity.BaseActivity;
import com.core.wigets.Alert;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import static com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW;
import static com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;

/**
 * Created by sreay on 14-11-4.
 */
public class ShareUtil {
    private static IWXAPI iwxapi = null;
    private static Tencent mTencent = null;

    public static IWXAPI initWXAPI(Context context, String WXAppID, boolean b) {
        //微信api
        iwxapi = WXAPIFactory.createWXAPI(context, WXAppID, b);
        iwxapi.registerApp(WXAppID);
        return iwxapi;
    }

    public static Tencent getTencent(Context context, String kQQAppID) {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(kQQAppID, context);
        }
        return mTencent;
    }

    /**
     * @param activity
     * @param title          分享的标题
     * @param content        分享的内容
     * @param shareUrl       分享的链接地址
     * @param pic_url        分享的图片地址
     * @param isTimeline     分享到朋友圈还是好友
     * @param wxMiniUserName 小程序的名称，也就是原始id
     * @param wxMiniPath     小程序的路径
     * @param isDevelop      当前运行的环境  true 非正式环境   false 正式环境
     */
    public static void shareToWeChat(Activity activity, String title, String content, String shareUrl, String pic_url, boolean isTimeline, String wxMiniUserName, String wxMiniPath, boolean isDevelop) {
        NiceLogUtil.d("小程序得环境：" + isDevelop);
        downloadImage(activity, title, content, shareUrl, pic_url, isTimeline, wxMiniUserName, wxMiniPath, isDevelop);
    }

    private static void shareToWeChat(String title, String content, String shareUrl, Bitmap thumBmp, boolean isTimeline, String wxMiniUserName, String wxMiniPath, boolean isDevelop) {
        //调用api接口发送数据到微信
        if (iwxapi == null || iwxapi.isWXAppInstalled() == false) {
            Alert.toast("未安装微信");
            return;
        }
        WXMediaMessage msg = null;
        if (TextUtils.isEmpty(title)) {
            title = "趣学车";
        }
        //不需要分享小程序
        if (TextUtils.isEmpty(wxMiniUserName)) {
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = shareUrl;
            msg = new WXMediaMessage(webpageObject);
        } else {
            WXMiniProgramObject wxMiniProgramObject = new WXMiniProgramObject();
            //低版本微信
            wxMiniProgramObject.webpageUrl = shareUrl;
            //高版本
            wxMiniProgramObject.userName = wxMiniUserName;
            wxMiniProgramObject.path = wxMiniPath;
            if (isDevelop) {
                wxMiniProgramObject.miniprogramType = MINIPROGRAM_TYPE_PREVIEW;
            } else {
                wxMiniProgramObject.miniprogramType = MINIPTOGRAM_TYPE_RELEASE;
            }
            msg = new WXMediaMessage(wxMiniProgramObject);
        }
        msg.title = title;
        msg.description = content;
        msg.setThumbImage(thumBmp);
        //下面的方法在小米手机中有问题
        //        msg.thumbData = BitmapUtils.bmpToByteArray(icon, true);
        //构造一个req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());//transaction字段用于唯一表示一个请求
        req.message = msg;
        if (isTimeline) {
            //分享到朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        } else {
            //分享给好友
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        if (iwxapi != null) {
            iwxapi.sendReq(req);
        }
    }

    private static void downloadImage(final Activity activity, final String title, final String content, final String shareUrl, String pic_url, final boolean isTimeline,

                                      final String wxMiniUserName, final String wxMiniPath, final boolean isDevelop) {
        ((BaseActivity) activity).showWaitDialog(true);
        Glide.with(CoreApplication.getInstance()).load(pic_url).asBitmap().fitCenter().into(new SimpleTarget<Bitmap>(100, 100) {

            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> transition) {
                ((BaseActivity) activity).dissmissWaitingDialog();
                shareToWeChat(title, content, shareUrl, resource, isTimeline, wxMiniUserName, wxMiniPath, isDevelop);
            }
        });
    }

    public static void shareToQQZoneUrl(Activity activity, String title, String content, String shareUrl, String imgUrl, IUiListener listener) {
        if (TextUtils.isEmpty(title)) {
            title = "趣学车";
        }
        if (mTencent != null) {
            final Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
            ArrayList<String> urls = new ArrayList<>();
            if (!TextUtils.isEmpty(imgUrl.trim())) {
                urls.add(imgUrl);
            }
            params.putStringArrayList(QQShare.SHARE_TO_QQ_IMAGE_URL, urls);
            params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "趣学车");
            mTencent.shareToQzone(activity, params, listener);
        }
    }

    public static void shareToQQUrl(Activity activity, String title, String content, String shareUrl, String imgUrl, IUiListener listener) {
        if (TextUtils.isEmpty(title)) {
            title = "趣学车";
        }
        if (mTencent != null) {
            NiceLogUtil.i("xxx==tencent != null");
            final Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
            if (!TextUtils.isEmpty(imgUrl)) {
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
            }
            params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "趣学车");
            mTencent.shareToQQ(activity, params, listener);
        }
    }

    public static void shareLocalPicToQQ(Activity activity, String localPath, IUiListener listener) {
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "趣学车");
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        mTencent.shareToQQ(activity, params, listener);
    }

    public static void shareLocalPicToQQZone(Activity activity, String localPath, IUiListener listener) {
        Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, localPath);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "趣学车");
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        mTencent.shareToQQ(activity, params, listener);
    }

    public static void shareBitmap(BaseActivity activity, String pic_url, final boolean isShareMoments) {
        downloadImage(activity, pic_url, isShareMoments);
    }

    private static void downloadImage(final BaseActivity activity, final String pic_url, final boolean isTimeline) {
        activity.showWaitDialog(true);
        Glide.with(CoreApplication.getInstance()).load(pic_url).asBitmap().fitCenter().into(new SimpleTarget<Bitmap>(250, 250) {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                activity.dissmissWaitingDialog();
                shareBitmapContent(bitmap, isTimeline);
            }
        });
    }

    public static void shareBitmapContent(Bitmap bitmap, final boolean isShareMoments) {
        //调用api接口发送数据到微信
        if (iwxapi.isWXAppInstalled() == false) {
            Alert.toast("未安装微信");
            return;
        }
        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        msg.setThumbImage(bitmap);
//        msg.thumbData = bitmapTobyteArrray(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = isShareMoments ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;

        if (iwxapi != null) {
            iwxapi.sendReq(req);
        }

    }

    public static void shareWxBitmapLarge(Bitmap bitmap, final boolean isShareMoments) {
        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = isShareMoments ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        if (iwxapi != null) {
            iwxapi.sendReq(req);
        }

    }

    private static byte[] bitmapTobyteArrray(Bitmap bitmap) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);//把bitmap100%高质量压缩 到 output对象里
        bitmap.recycle();//自由选择是否进行回收
        byte[] result = output.toByteArray();//转换成功了
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
